package sunwin.yoms.web.comm.controllerAspect;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import sunwin.yoms.service.security.YomsUserDetails;
import sunwin.yoms.web.comm.R;
import sunwin.yoms.web.comm.YomsController;
import sunwin.yoms.web.comm.YomsControllerDefaultData;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * Created by 田西泽 on 2015-8-26.
 * 将共享数据注入到ModelMap中
 */
@Component
public class ShareDataAspect {

    @Autowired
    private R r;
    @Autowired
    private YomsControllerDefaultData defaultData;

    /**
     * 重构ModelAndView
     *
     * @param handler
     * @param modelAndView
     */
    public void refactorModelAndView(HttpServletRequest request, HandlerMethod handler, ModelAndView modelAndView) {
        if (modelAndView == null) {
            modelAndView = new ModelAndView();
        }
        YomsController yomsController = getAnnotation(handler);
        /*
        ModelAndView中的viewName必须设置为YomsController的viewName. 否则抛出YomsException异常将不能发送到客户端
         */
        if (yomsController != null) {
            modelAndView.setViewName(yomsController.viewName());
        }

        CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
        if (csrfToken != null) {
            modelAndView.addObject("_csrf", csrfToken);
        }

        modelAndView.addObject("nickname", getNickname());
        modelAndView.addObject("r", r);
    }

    /**
     * 获取用户昵称
     *
     * @return
     */
    private String getNickname() {
        YomsUserDetails details = defaultData.getCurrentYomsUserDetails();
        if (details != null) {
            return details.getNickname();
        }
        return "NULL";
    }

    /**
     * 获取YomsController注解
     *
     * @param handler
     * @return
     */
    private YomsController getAnnotation(HandlerMethod handler) {
        Method method = handler.getMethod();
        return method.getAnnotation(YomsController.class);
    }
}
